package handler

import (
	"api/pkg"
	__ "api/proto"
	"api/request"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"path/filepath"
)

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	if file == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "文件获取失败",
			"data": nil,
		})
		return
	}
	ext := filepath.Ext(file.Filename)
	if ext != ".png" && ext != ".jpg" {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "文件类型错误",
			"data": nil,
		})
		return
	}
	if file.Size > 5*1024*1024 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "文件过大 请重新上传",
			"data": nil,
		})
		return
	}
	uuid := uuid.NewString()
	dst := "./static/upload" + uuid + filepath.Ext(file.Filename)
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)

	pkg.UploadOss(dst, file.Filename)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"data": pkg.GetOssFileUrl(file.Filename),
	})

}

func List(c *gin.Context) {
	var req request.List
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c1 := __.NewExamClient(conn)
	list, err := c1.List(c, &__.ListRequest{})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "展示失败",
			"data": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})
	return
}
